package com.github.MrWub.key;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;

import com.github.MrWub.SWskillAPI;
import com.github.MrWub.key.event.KeyPressEvent;
import com.github.MrWub.key.event.PreKeyPressEvent;

public class KeyPressCatcher implements PluginMessageListener{
	private int bytesToInt(byte[] b) {
		int sing = 0xff; //1111 1111
		int result = 0;
		for (int i = 0; i<4; i++) {
			result <<= 8;
			int temp = b[i] & sing;
			result |= temp;
		}
		return result;
	}
	
	public KeyPressCatcher(SWskillAPI sw) {
		Bukkit.getMessenger().registerIncomingPluginChannel(sw, "swskill", this);
	}
	
	@Override
	public void onPluginMessageReceived(String name, Player player, byte[] bytes) {
		if (!name.equalsIgnoreCase("swskill")) {
			return;
		}
		int key = bytesToInt(bytes);
		KeyOption option = KeyManager.getKeyOption(player.getName().toLowerCase());
		if (option == null) return;
		if (!option.isCatch()) return;
		if (option.getKeySkill(key) != null) {
			PreKeyPressEvent pkpe = new PreKeyPressEvent(player, key);
			Bukkit.getPluginManager().callEvent(pkpe);
			if (pkpe.isCancelled()) {
				return;
			}
			
			KeyPressEvent kpe = new KeyPressEvent(player, key);
			Bukkit.getPluginManager().callEvent(kpe);
		}
	}
	
}